import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import json

from score_info import ScoreInfo
"""学生信息前端实现：数据状态存储csv文件中
   字段：学生编号 id_no,姓名 name,性别 sex,年龄 age,班级 cls,地址 addr
   样例：9001,张飞,男,19,科创一班,深圳南山一路
"""
from student_info import StudentInfo
class StudentWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("学生成绩管理")
        self.root.title("学生成绩管理")
        self.root.geometry("600x400")
        # 初始化数据

        #学生编号 id_no,姓名 name,性别 sex,年龄 age,班级 cls,地址 addr
        #9001,张飞,男,19,科创一班,深圳南山一路
        # self.data = [
        #     {"id_no": 9001, "name": "张飞", "sex": "男", "age": 19, "cls": "科创一班", "addr": "深圳南山一路"},
        #     {"id_no": 9002, "name": "关羽", "sex": "男", "age": 20, "cls": "科创二班", "addr": "深圳南山一路"},
        #     {"id_no": 9003, "name": "赵云", "sex": "男", "age": 21, "cls": "科创一班", "addr": "深圳南山一路"},
        # ]
        # 从student_data.csv文件中读取数据 @todo
        self.data = StudentInfo.read_student_data()



        # 创建搜索框
        self.search_frame = ttk.Frame(root)
        self.search_frame.pack(pady=5)

        ttk.Label(self.search_frame, text="学生编号:").pack(side=tk.LEFT, padx=2)
        self.search_entry = ttk.Entry(self.search_frame, width=20)
        self.search_entry.pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_frame, text="搜索", command=self.search_data).pack(side=tk.LEFT, padx=2)

        # 创建表格
        self.tree = ttk.Treeview(root, columns=("id_no", "name", "sex", "age", "cls", "addr"), show="headings")
        self.tree.heading("id_no", text="学生编号",anchor=tk.W)
        self.tree.heading("name", text="姓名",anchor=tk.W)
        self.tree.heading("sex", text="性别",anchor=tk.W)
        self.tree.heading("age", text="年龄",anchor=tk.W)
        self.tree.heading("cls", text="班级",anchor=tk.W)
        self.tree.heading("addr", text="地址",anchor=tk.W)
        self.tree.pack(pady=5)
        # 设置表格列宽
        for col in ("id_no", "name", "sex", "age", "cls", "addr"):
            self.tree.column(col, width=100)

        # 按钮框架
        btn_frame = ttk.Frame(root)
        btn_frame.pack(pady=5)
        ttk.Button(btn_frame, text="新增", command=self.show_add_dialog).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="修改", command=self.show_edit_dialog).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="删除", command=self.delete_data).pack(side=tk.LEFT, padx=10)

        self.refresh_table()

    def refresh_table(self):
        for item in self.tree.get_children():
            self.tree.delete(item)
        for item in self.data:
            self.tree.insert("", "end", values=(
                item["id_no"], item["name"], item["sex"],
                item["age"], item["cls"], item["addr"]
            ))

    def search_data(self):
        search_id = self.search_entry.get()
        if not search_id:
            self.refresh_table()
            return
        filtered_data = [item for item in self.data if str(item["id_no"]) == search_id]
        self.data = filtered_data
        self.refresh_table()

    def show_add_dialog(self):
        dialog = tk.Toplevel(self.root)
        dialog.title("新增学生")

        fields = ["id_no", "name", "sex", "age", "cls", "addr"]
        col_dict={"id_no":"学生编号","name":"姓名","sex":"性别","age":"年龄","cls":"班级","addr":"地址"}
        entries = {}
        for i, field in enumerate(fields):
            #转换成相关对应的标签字段
            ttk.Label(dialog, text=col_dict[field]).grid(row=i, column=0, padx=2, pady=2)
            entries[field] = ttk.Entry(dialog)
            entries[field].grid(row=i, column=1, padx=2, pady=2)

        ttk.Button(dialog, text="确认", command=lambda: self.add_data(entries, dialog)).grid(row=6, columnspan=2,
                                                                                             pady=5)

    def add_data(self, entries, dialog):
        try:
            new_data = {
                "id_no": int(entries["id_no"].get()),
                "name": entries["name"].get(),
                "sex": entries["sex"].get(),
                "age": int(entries["age"].get()),
                "cls": entries["cls"].get(),
                "addr": entries["addr"].get()
            }
            self.data.append(new_data)
            dialog.destroy()
            self.refresh_table()
            #  把内存数据写入到文件中,采用csv格式 @todo
            StudentInfo.write_student_data(self.data)


        except ValueError:
            messagebox.showerror("错误", "输入数据格式错误")

    def show_edit_dialog(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("提示", "请选择要修改的行")
            return

        item = self.tree.item(selected[0])
        data = {
            "id_no": item["values"][0],
            "name": item["values"][1],
            "sex": item["values"][2],
            "age": item["values"][3],
            "cls": item["values"][4],
            "addr": item["values"][5]
        }

        dialog = tk.Toplevel(self.root)
        dialog.title("修改学生")

        fields = ["id_no", "name", "sex", "age", "cls", "addr"]
        col_dict = {"id_no": "学生编号", "name": "姓名", "sex": "性别", "age": "年龄", "cls": "班级", "addr": "地址"}
        entries = {}
        for i, field in enumerate(fields):
            ttk.Label(dialog, text=col_dict[field]).grid(row=i, column=0, padx=2, pady=2)
            entries[field] = ttk.Entry(dialog)
            entries[field].insert(0, data[field])
            entries[field].grid(row=i, column=1, padx=2, pady=2)

        ttk.Button(dialog, text="确认", command=lambda: self.edit_data(entries, dialog, data["id_no"])).grid(row=6,
                                                                                                             columnspan=2,
                                                                                                             pady=5)

    def edit_data(self, entries, dialog, original_id):
        try:
            for item in self.data:
                if item["id_no"] == original_id:
                    item.update({
                        "id_no": int(entries["id_no"].get()),
                        "name": entries["name"].get(),
                        "sex": entries["sex"].get(),
                        "age": int(entries["age"].get()),
                        "cls": entries["cls"].get(),
                        "addr": int(entries["addr"].get())
                    })
                    break
            dialog.destroy()
            self.refresh_table()
            #  把内存数据写入到文件中,采用csv格式 @todo
            StudentInfo.write_student_data(self.data)


        except ValueError:
            messagebox.showerror("错误", "输入数据格式错误")

    def delete_data(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("提示", "请选择要删除的行")
            return

        if messagebox.askyesno("确认", "确定要删除吗？"):
            item = self.tree.item(selected[0])
            id_no = int(item["values"][0])
            self.data = [item for item in self.data if item["id_no"] != id_no]
            self.refresh_table()
            #  把内存数据写入到文件中,采用csv格式 @todo
            StudentInfo.write_student_data(self.data)




'''测试用例代码'''
if __name__ == "__main__":
    root = tk.Tk()
    app = StudentWindow(root)
    root.mainloop()